<?php
/* 
	微信commonModel
 */

class Model_Com extends Model_Table{
	
	/* 
		本地拉取微信全局access_token 若本地无token 则调用微信接口	
	*/
	static function getWxToken($cusid=1333,$renovate=false){
	
		//配置表 查询access_token
		$cusconfModel = new Model_CustomerConfig();
		
		//是否需要刷新token
		if($renovate){
			$token = self::getAnewToken($cusconfModel,$cusid);
			return $token;
		}
		
		$where = "customer_id='$cusid' and c_type='appid'";
		$field = "token,valid_time";
		$tokenInfo = $cusconfModel->findRow($where,$field);
		
		//判断token 是否存在
		if($tokenInfo){
			//token存在 继续判断是否过期
			if($tokenInfo['token'] && $tokenInfo['valid_time'] > time()){
				return $tokenInfo['token'];
			}else{
				return self::getAnewToken($cusconfModel,$cusid);
			}
			
		//不存在 调用微信接口
		}else{
			$token = self::getAnewToken($cusconfModel,$cusid);
			return $token;
		}
	}
	
	/* 
		调用微信接口拉取access_token
	*/
	static function getAnewToken($cusconfModel='',$cusid=1){
		//本地查询 appid secret
		$wxConfig = $cusconfModel->findRow("c_type = 'appid'",'c_value');
		//判断 本地是否配置appid与secret
		if($wxConfig['c_value']){
			$info = explode(',',$wxConfig['c_value']);
			$appid = $info[0];
			$secre = $info[1];
		}else{
			ajax_feedback(0,'local101','请先配置微信APPID与SECRET');
		}
		
		//调用微信接口获取token
		$getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secre";
		$wxBack = Model_PostCurl::wx_send($getTokenUrl);
		
		if($token = $wxBack['access_token']){
			self::saveToken(array('token'=>$token),$cusconfModel,$cusid);
			return $token;
		}else{
			ajax_feedback(0,'wx101','获取全局access_token失败，微信返回码：'.$wxBack['errcode']);
		}
	}
	
	/* 
		保存token至本地 customer_config数据表
	*/
	static function saveToken($tokenArray=array(),$cusconfModel='',$cusid){
		//$tokenArray['c_type'] = 'appid';
		$tokenArray['valid_time'] = time()+3600;
		$cusconfModel->row_update($tokenArray,"customer_id='$cusid' and c_type='appid'");
	}
	
	/* 
		从微信拉取关注用户的openid
	*/
	static function renovateUserList($token='',$agin=false){
		//微信接口 拉取用户列表
		
		$next = $agin ? "&next_openid=$agin" : '';
		$userListApiUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$token".$next;
		$result = Model_PostCurl::wx_send($userListApiUrl);
	
		//错误处理
		if($result['errcode']){
			//若access_token失效 则刷新
			if($result['errcode']=='40001'){
				set_time_limit(0);
				$newToken = self::getWxToken($_SESSION['customer_id'],'renovate');
				self::renovateUserList($newToken);
			}else{
				ajax_feedback(0,'wx102','接口调用失败，微信返回码：'.$result['errmsg']);
			}
		}
		self::saveOpenid($result['data']['openid']);
		$next_openid = $result['next_openid'];
		
		if($result['count']==10000){
			self::renovateUserList($token,$result['next_openid']);
		}
	}
	
	/* 
		保存用户信息至数据库
	*/
	static function saveOpenid($userArray){
		if(is_array($userArray) && !empty($userArray)){
			$countNum = count($userArray);
			
			foreach($userArray as $val){
				$data .= "('".$_SESSION['customer_id']."','".$val."','1'),";
			}
			$sql = "insert into member (`customer_id`,`fromuser`,`is_update`) values ".rtrim($data,',');
		
			$memberModel = new Model_Member();
			$insertBack = $memberModel->query($sql);
			
			if(is_int($insertBack)){return ;}
		}
		ajax_feedback(0,'local102','无用户信息或数据库写入失败'.$insertBack);
	}
	
	/* 拉取分组列表 */
	static function renovateGroupList($token){
		$getApi   = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$token";
		$groupMsg = Model_PostCurl::wx_send($getApi);
		
		if($groupMsg['errcode']){
			if($groupMsg['errcode']==40001){
				$newToken = self::getWxToken($_SESSION['customer_id'],'renovate');
				self::renovateGroupList($newToken);
			}else{
				ajax_feedback(0,'wx103','拉取分组列表失败，微信返回码：'.$groupMsg['errmsg']);
			}
		}
		self::saveGroup($groupMsg['groups']);
	}
	
	/* 
		保存分组至本地
	*/
	static function saveGroup($groupArray){
		if(is_array($groupArray) && !empty($groupArray)){
			foreach($groupArray as $val){
				$data .= "('".$val['name']."','$val[id]','2'),";
			}
			$sql = "insert into wx_group (`group_name`,`group_id`,`status`) values ".rtrim($data,',');
		}

		$groupModel = new Model_WxGroup();
		$insertBack = $groupModel->query($sql);
		if(is_int($insertBack)){return ;}
		ajax_feedback(0,'local103','无分组列表或数据库写入失败'.$insertBack);
	}
	
	//上传图片至微信服务器
	static function upImageToWx($imagePath){
	
		$token = self::getWxToken();
		$upFileUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$token&type=image";
		$imgPath   = realpath($imagePath);
		$data 	   = array('media'=>'@'.$imgPath);
		$info 	   = Model_PostCurl::wx_send($upFileUrl,$data);
		
		return $info['media_id'];	
	}
	
	//微信场景二维码接口 
	static function get_scene_qrcode ($id) {
		
		$token = self::getWxToken();
		
		$api_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token;
		
		$data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
		
		$ticket_info = Model_PostCurl::wx_send($api_url,$data);
		
		if ($ticket_info['ticket'] && $ticket_info['url']) {
			return $ticket_info['url'];
		}
	}
	
}

?>